<?php
class Db {
    public $pdo;
    private $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    public function __construct() {
        $db_config = include('config/db.php');
        $dsn="mysql:dbname={$db_config['dbname']};host={$db_config['host']};charset={$db_config['charset']}";
        try {
            $this->pdo = new PDO($dsn, $db_config['user'], $db_config['pass'], $this->options);
        } catch (\PDOException $e) {
            throw new \PDOException($e->getMessage(), (int)$e->getCode());
        }
    }

    public function query($query) {
        $stmt = $this->pdo->query($query);
        return $stmt->fetchAll();
    }

    public function query1($sql, $params = [])
    {
        $stmt = $this->pdo->prepare($sql);
        foreach ($params as $key => $param) {
            $stmt->bindParam($key, $param['data'], $param['type'] ?: PDO::PARAM_STR);
        }
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function execute($query, $params = []) {
        $stmt = $this->pdo->prepare($query);
        $stmt->execute($params);
        return $stmt->rowCount();
    }

    public function lastInsertId() {
        return $this->pdo->lastInsertId();
    }

}

//// 使用示例
//$db = new Db();
//
//// 查询
//$results = $db->query('SELECT * FROM users');
//print_r($results);
//
//// 插入
//$inserted = $db->execute('INSERT INTO users (username, email) VALUES (:username, :email)', [
//    ':username' => 'newuser',
//    ':email' => 'newuser@example.com'
//]);
//echo "Rows inserted: " . $inserted;
//
//// 获取最后插入的ID
//echo "Last inserted ID: " . $db->lastInsertId();